package com.shiro.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.shiro.pojo.AuthorityBean;
import com.shiro.pojo.RoleBean;
import com.shiro.pojo.UserBean;
import com.shiro.service.UserService;

public class UserRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory
			.getLogger(UserRealm.class);
	@Autowired
	private UserService userService;
	
	

	@Override
	public String getName() {
		return getClass().getName();
	}

	/**
	 * 授权
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		logger.info("-------------授权启动了--------------");
		UserBean user = (UserBean)principals.getPrimaryPrincipal();
		List<RoleBean> list1 = userService.findRoleByUsername(user.getUsername());
		List<AuthorityBean> list2 = userService.findAuthorityByUsername(user.getUsername());
		Set<String> roles = new HashSet<String>();
		Set<String> permiss = new HashSet<String>();
		for(RoleBean r:list1){
			roles.add(r.getName());
		}
		for(AuthorityBean r:list2){
			permiss.add(r.getName());
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRoles(roles);
		info.addStringPermissions(permiss);
		return info;
	}
	

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		logger.info("-------------认证启动了--------------");
		String str = (String) token.getPrincipal();
        UserBean user=userService.findUserByUserName(str);
		if (user == null) {
			// 用户名不存在抛出异常
			logger.debug("认证：当前登录的用户不存在");
			throw new UnknownAccountException();
		}
		Subject subject = SecurityUtils.getSubject();
		subject.getSession().setAttribute("user",user);
		String pwd = user.getPassword();
		return new SimpleAuthenticationInfo(user, pwd, getName());
	}

}
